const express = require("express");
const router = express.Router();
const fs = require("fs");
const path = require("path");
const ResponseHelper = require("../ResponseHelper");
const { mkdir2,mkdir3 } = require("../../tools");
const RecordInfoServer = require("../../servers/RecordInfo");
const ImgParamServer = require("../../servers/ImgParam");
const fileUrl = require("../../tools/fileUrl");

router.post("/", async (req, res, next) => {
  try {
    var params = req.body;
    if (!params.UUID) {+
      console.log("++++++++++++++++++++++没有uuid");
      return;
    }
    if (!params.SaveImageData || !params.SaveImageData.imageName) {
      console.log("+++++++++++++++++++++++没有imageName");
      return;
    }
    if (!params.SaveImageData.imageData) {
      console.log("+++++++++++++++++++++++没有imageData");
      return;
    }
    if (!params.ImageParam) {
      console.log("+++++++++++++++++++++++没有ImageParam");
      return;
    }
    if(!params.SaveSubDir){
      console.log("+++++++++++++++++++++++没有SaveSubDir");
      return;
    }
    console.log(
      "+++++++++++++++++++++++图像params:",
      params.SaveSubDir
    );
    // var imgpath = `${fileUrl.uploadStaticPath}/${params.UUID}`;
    var new_imgpath = `${fileUrl.uploadStaticPath}/${params.SaveSubDir}`
    var fileName = params.SaveImageData.imageName.trim();
    // await mkdir2(imgpath);
    await mkdir3(new_imgpath);
    var base64 = params.SaveImageData.imageData.replace(
      /^data:image\/\w+;base64,/,
      ""
    ); //去掉图片base64码前面部分data:image/png;base64
    var dataBuffer = new Buffer(base64, "base64"); //把base64码转成buffer对象
    var imgPathUrl = path.join(new_imgpath, `${fileName}.jpg`);
    console.log("+++++++++++++++++++++++imgPathUrl", imgPathUrl);
    fs.writeFile(imgPathUrl, dataBuffer, async function (err) {
      //用fs写入文件
      if (err) {
        console.log("+++++++++++++++++++++++err", err);
        ResponseHelper.sendErr(err, res);
      } else {
        const type = params.type ? params.type : "local";
        const imgInfo = {
          pid: params.UUID,
          id: fileName,
          url: `http://${req.headers.host}/pubilc/uploads/${params.SaveSubDir}/${fileName}.jpg`,
          type,
        };
        console.log("+++++++++++++++++++++++保存的图片imgInfo:", imgInfo);
        const record = await RecordInfoServer.getById(params.UUID);
        const reportimg = record.reportimg;
        let reportimgVal;
        if (reportimg) {
          reportimgVal = JSON.parse(reportimg);
          reportimgVal.push(imgInfo);
        } else {
          reportimgVal = [];
          reportimgVal.push(imgInfo);
        }
        const updateReportimg = JSON.stringify(reportimgVal);
        const updateReportRes = await RecordInfoServer.update(params.UUID, {
          reportimg: updateReportimg,
        });
        console.log("+++++++++++++++++++++++检查记录更新结果:", updateReportRes);
        if (updateReportRes.length > 0) {
          ResponseHelper.sendData(
            `http://${req.headers.host}/pubilc/uploads/${params.SaveSubDir}/${fileName}.jpg`,
            res
          );
        } else {
          ResponseHelper.sendErr(`上传失败!`, res);
        }
        const img_param = JSON.stringify(params.ImageParam);
        if (img_param) {
          const add_param = {
            id: fileName,
            params: img_param,
          };
          const arrParam_res = await ImgParamServer.addImgParam(add_param);
          console.log("+++++++++++++++++++++++保存图片参数结果:", arrParam_res);
        }
      }
    });
  } catch (err) {
    console.log("+++++++++++++++++++++++err", err);
    ResponseHelper.sendErr(err, res);
  }
});

module.exports = router;
